package com.glq1218.filter;

import com.glq1218.enums.ResultEnum;
import com.glq1218.exception.CustomException;
import com.glq1218.util.JwtUtils;
import com.glq1218.util.RedisUtils;
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义jwt过滤器
 */
@Component
public class CustomOncePerRequestFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtils redisUtils;
    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)){
            String username = JwtUtils.parseJWT(token).getSubject();
            if (StringUtils.hasText(username)){
                String tokenInRedis = redisUtils.get("token" + username);
                if (token.equals(tokenInRedis)){
                    filterChain.doFilter(request,response);
                }
                throw new CustomException(ResultEnum.NO_LOGIN);
            }
            throw  new CustomException(ResultEnum.NO_TOKEN);
        }
        filterChain.doFilter(request, response);
    }
}
